package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.mapper.CurrentPerformanceDataMapper;
import com.ruoyi.cpsp.service.*;
import com.ruoyi.web.controller.cpsp.EmployeeController;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/*
    @author neu.xiangwenjuan
    @create 2022/7/14
*/
@Component("timingTask")
public class TimingTaskImpl {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PerformanceHistoryService performanceHistoryService;

    @Autowired
    private EvaluateRecordService evaluateRecordService;

    @Autowired
    private CurrentPerformanceDataService currentPerformanceDataService;

    @Autowired
    private CurrentPerformanceDataMapper currentPerformanceDataMapper;

    @Autowired
    private PreviousPerformanceDataService previousPerformanceDataService;


    @Autowired
    private EvaluateRecordToEmployeeService toEmployeeService;

    @Autowired
    private EvaluateRecordDetailService detailService;


    private EmployeeController employeeController = new EmployeeController();

    // @Scheduled(cron = "0 0 0 * * ?")每天凌晨运行一次 更新员工数据
    private void updateEmployeeInfo() {
        List<EmployeeEntity> employees = employeeService.selectAll();
        if (employees.size() == 0) {
            employeeController.insertEmployeeToTable();
        }else {
            // 通过甲方提供的接口获得员工信息。
            Object object = employeeController.testPost("user",new EmployeeFromCompany());
            String json = JSON.toJSONString(object);
            EmployeeFromCompany employeeFromCompany = JSONObject.parseObject(json, EmployeeFromCompany.class);
            EmployeeFromCompanyData[] employeeDatas = employeeFromCompany.getData();
            for (EmployeeFromCompanyData employee : employeeDatas) {
                boolean flag = false;
                for (EmployeeEntity employeeEntity : employees) {
                    if (employee.getIdcard().equals(employeeEntity.getIdCard())) {
                        flag = true;
                        if (!employeeEntity.getDepartment().getDepartmentId().equals(employee.getDwh_id())) {
                            Employee employeeInfo = new Employee();
                            employeeInfo.setId(employeeEntity.getId());
                            employeeInfo.setDepartmentId(employee.getDwh_id());
                            int tag = employeeService.updateByPrimaryKeySelective(employeeInfo);
                            if (tag > 0) {
                                System.out.println("更新员工表成功！");
                            }else  {
                                System.out.println("更新员工表失败！");
                            }
                        }
                    }
                }
                if (!flag) {// 说明该员工在人事系统中存在，但在绩效系统中不存在。 需要插入到系统中。
                    int dateFlag    = employeeController.getPassDaySeason(new Date());
                    String  name            = employee.getName(),
                            idCard          = employee.getIdcard(),
                            jobNumber       = employee.getId(),
                            positionType    = employee.getPosition(),
                            departmentId    = employee.getDwh_id();

                    int is45Days = dateFlag>employeeController.getCountBetweenTwoDates(employee.getStart(), new Date()) ? dateFlag: employeeController.getCountBetweenTwoDates(employee.getStart(), new Date());

                    Employee insertEmployee = new Employee(name, idCard, jobNumber, is45Days, positionType, departmentId);
                    boolean tag = employeeService.submitAllInfo(insertEmployee);
                    if (tag) {
                        System.out.println("插入新员工成功！");
                    }else {
                        System.out.println("插入新员工成功！");
                    }
                }
            }
        }
    }
//    // @Scheduled(cron = " 0 00 00 1 4,7,10,1 ?") 每个季度的第一天运行一次.
//    private void updatePerformanceQuarter() {
//        // 每个季度结束时，需要更新下一季度绩效的初值，其中生产岗累加100，辅助岗累加50。
//        // 得到当前年份和季度。
//        Calendar calendar = Calendar.getInstance();
//        Integer year = calendar.get(Calendar.YEAR);
//        int quarter = employeeController.getSeason(new Date());
//        // 上季度的绩效的初始值。
//        List<PerformanceHistory> histories = new ArrayList<>();
//        List<EvaluateRecordCurrentQuarter> sumProp = new ArrayList<>();
//        if (quarter > 1) {
//            histories = performanceHistoryService.selectPerformanceValue(year, quarter - 1);
//            sumProp = evaluateRecordService.getMaxProp(year,quarter - 1);
//        }else {
//            histories = performanceHistoryService.selectPerformanceValue(year - 1,4);
//            sumProp = evaluateRecordService.getMaxProp(year - 1,4);
//        }
//        // 先计算上季度绩效的实际值。
//        for (EvaluateRecordCurrentQuarter sum : sumProp) {
//            for (PerformanceHistory history:histories) {
//                if (sum.getEmployeeIdCard().equals(history.getEmployeeIdCard())) {
//                    if (sum.getMaxProp() > 1)
//                        history.setPerformanceValue(0.0);
//                    history.setPerformanceValue(history.getPerformanceValue() * (1 - sum.getMaxProp()));
//                }
//            }
//        }
//        // 不得更新上一季度的历史绩效信息嘛。
//        for (PerformanceHistory history :histories) {
//            performanceHistoryService.updateByPrimaryKeySelective(history);
//        }
//        // 需要先更新本季度的绩效值。
//        for (PerformanceHistory history : histories) {
//            if (employeeService.getIsDirectProducer(history.getEmployeeIdCard()) != null && employeeService.getIsDirectProducer(history.getEmployeeIdCard())) {
//                if (history.getPerformanceValue() <= 900)
//                    history.setPerformanceValue(history.getPerformanceValue() + 100);
//                history.setPerformanceValue(1000.0);
//            }else {
//                if (history.getPerformanceValue() <= 450)
//                    history.setPerformanceValue(history.getPerformanceValue() + 50);
//                history.setPerformanceValue(500.0);
//            }
//            history.setYear(year);
//            history.setQuarter(quarter);
//            history.setId(null);
//            performanceHistoryService.insert(history);
//        }
//    }

    /**
     * @Scheduled(cron = " 0 00 00 1 4,7,10,1 ?")
     */
    // 每个季度的第一天运行,将current_performance_data表中数据添加到previous_performance_data
    public void updatePreviousPerformanceData() {
        List<CurrentPerformanceData> currentPerformanceData = currentPerformanceDataService.getAllInfo(null);
        for (int i = 0; i < currentPerformanceData.size(); i++) {
            PreviousPerformanceData previousPerformanceData = new PreviousPerformanceData();
            previousPerformanceData.setCumulativeBase(currentPerformanceData.get(i).getCumulativeBase());
            previousPerformanceData.setCurrentBase(currentPerformanceData.get(i).getCurrentBase());
            previousPerformanceData.setEmployeeIdCard(currentPerformanceData.get(i).getEmployeeIdCard());
            previousPerformanceData.setEvaluateRecordId(currentPerformanceData.get(i).getEvaluateRecordId());
            previousPerformanceData.setIncreaseBase(currentPerformanceData.get(i).getIncreaseBase());
            previousPerformanceData.setMoneyEveryMonth(currentPerformanceData.get(i).getMoneyEveryMonth());
            previousPerformanceData.setMoneyQuarter(currentPerformanceData.get(i).getMoneyQuarter());
            previousPerformanceData.setOnWork(currentPerformanceData.get(i).getOnWork());
            previousPerformanceData.setProportionOfPunishment(currentPerformanceData.get(i).getProportionOfPunishment());
            previousPerformanceData.setQuarter(currentPerformanceData.get(i).getQuarter());
            previousPerformanceData.setValueOfPunishment(currentPerformanceData.get(i).getValueOfPunishment());
            previousPerformanceData.setYear(currentPerformanceData.get(i).getYear());
            previousPerformanceData.setAnnotation(currentPerformanceData.get(i).getAnnotation());
            int tag = previousPerformanceDataService.insert(previousPerformanceData);
        }
        // 每个季度的第一天运行,将current_performance_data表中数据更新。
        boolean flag = updateCurrentPerformanceData();
    }
    public boolean updateCurrentPerformanceData() {
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int quarter = calendar.get(Calendar.MONTH) / 3 + 1;
        // day应该是当前月份和后面两个月份，天数之和
        int day1 = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.MONTH, 1);
        int day2 = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.MONTH, 1);
        int day3 = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        int daySum = day1 + day2 + day3;
        // 当前测试一次
//        year = 2024; quarter = 1; daySum = 91;
        // TODO 需要从cpd里面筛选出正常的员工，对于状态为2的为已经删除的员工，不更新。还没删除,已经删除,state为2，表示筛选状态不为2的员工。
        List<CurrentPerformanceData> data = currentPerformanceDataService.getAllInfo(2);
        // 将已经离职的员工的绩效信息删除，这样就不会添加到下一个季度的绩效数据中。
        currentPerformanceDataService.deleteCurrentPerformanceData();
        double cumulativeBase;
        for (int i = 0; i < data.size(); i ++) {
            data.get(i).setYear(year); data.get(i).setQuarter(quarter);
            cumulativeBase = data.get(i).getCurrentBase();
            data.get(i).setCumulativeBase(cumulativeBase);
            data.get(i).setEvaluateRecordId("");
            boolean isDirect = employeeService.getIsDirectProducer(data.get(i).getEmployeeIdCard());
            if (isDirect) {
                if (cumulativeBase >= 1000) {
                    data.get(i).setIncreaseBase(0);
                }else if (cumulativeBase > 900){
                    data.get(i).setIncreaseBase(1000 - cumulativeBase);
                }else {
                    data.get(i).setIncreaseBase(100.0);
                }
            }else {
                if (cumulativeBase >= 500) {
                    data.get(i).setIncreaseBase(0);
                }else if (cumulativeBase > 450){
                    data.get(i).setIncreaseBase(500 - cumulativeBase);
                }else {
                    data.get(i).setIncreaseBase(50.0);
                }
            }
            data.get(i).setProportionOfPunishment(0.0);
            data.get(i).setValueOfPunishment(0.0);
            double currentBase = cumulativeBase + data.get(i).getIncreaseBase();
            data.get(i).setCurrentBase(currentBase);
            data.get(i).setMoneyEveryMonth(currentBase);
            data.get(i).setMoneyQuarter(currentBase * 3);
            data.get(i).setOnWork(daySum);
            data.get(i).setAnnotation("无");
            int flag = currentPerformanceDataService.updateByPrimaryKeySelective(data.get(i));
        }
        return true;
    }

    public void updateCurrentPerformance() {
        // 获取所有evaluateRecord的记录
        List<EvaluateRecord> evaluateRecords = evaluateRecordService.selectEvaluateRecords(2023, 4);

        // 获取对应的to_employee中所有员工身份证号
        for (EvaluateRecord evaluateRecord : evaluateRecords) {
            List<String> employeeIdCards = toEmployeeService.selectIdCardsByRecordId(evaluateRecord.getId());
            // 查询对应的扣减比例信息
            // 更新这些员工的信息
            detailService.updateCurrentPerformanceData(employeeIdCards, null);
        }
    }
}
